package com.gong.gongcloudpicture1.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.exception.ThrowUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;


/**
 * 文件上传
 */
@Service //这个是要被使用的, 所以加上这个注解
public class FilePictureUpload extends PictureUploadTemplate {


    /**
     * 文件大小
     * 1M
     */
    private static final long MAX_SIZE = 1024 * 1024;



    /**
     * 校验输入源(本地文件或者url)
     *
     * @param inputSource
     */
    @Override
    protected void checkPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //判断是否为空
        ThrowUtils.throwIf(multipartFile == null, new BusinessException(ErrorCode.PARAMS_ERROR, "上传的图片不存在!"));
        //判断图片大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 5 * MAX_SIZE, new BusinessException(ErrorCode.PARAMS_ERROR, "图片大小不可以超过5M!"));
        //校验文件后缀名
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> SUFFIX_LIST = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(!SUFFIX_LIST.contains(fileSuffix), new BusinessException(ErrorCode.PARAMS_ERROR, "仅支持jpg, png, jpeg格式的图片上传!"));
    }

    /**
     * 获取输入源的原始文件名
     *
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    /**
     * 处理输入源并生成本地临时文件
     *
     * @param inputSource
     * @param file
     */
    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
